const log4js = require("../public/javascripts/log4js")
const _md5 = require("md5");
const {db_control} = require("../DB/index")
const sqlString = require("sqlstring-sqlite")
const {YJY} = require("../public/javascripts/config")

class middleware {
	/**
	 * @description: 路由统一格式的中建间
	 * @author: 王琛
	 * @Date: 2023-02-23 19:45:14
	 * @param {*}
	 * @return {*}
	 */
	routerResponse(option = {}) {
		return async function (ctx, next) {
			ctx.success = function (data) {
				const corresponding_obj = {
					code: option.successCode || 200,
					msg: option.successMsg || 'success',
					data: data
				}
				ctx.type = option.type || 'json'
				ctx.body = corresponding_obj
				
				// 日志输入
				log4js.info(JSON.stringify(corresponding_obj))
			}
			
			ctx.fail = function (msg, code) {
				const corresponding_obj = {
					code: code || option.failCode || 99,
					msg: msg || option.successMsg || 'fail',
				}
				ctx.type = option.type || 'json'
				ctx.body = corresponding_obj
				// 日志输入
				log4js.error(JSON.stringify(corresponding_obj))
			}
			
			await next()
		}
	}
	
	/**
	 * @description: 用户验证的中间件  非页面验证 验证规则 MD5(用户名;秘钥;uuid)  注:uuid是用客户端提供
	 * @author: 王琛
	 * @Date: 2023-02-23 19:45:26
	 * @param {*}
	 * @return {*}
	 */
	function
	
	async userAuthentication(ctx, next) {
		const _body = ctx.request.body;
		let verificationOk = false;
		// 判断是否是意境云的推送数据
		if (ctx.method == "POST" && ctx.url == "/yjy/point/push") {
			// 开始拼接参数
			verificationOk = _md5(`${_body.timestamp}${YJY.secretKey}`).toLocaleLowerCase() == _body.access_token.toLocaleLowerCase();
		} else if (ctx.method == "POST" && ctx.url == "/fgz/warningInfo") {
			// 获取当前的用户信息
			const cur_user_info = await db_control({
				name: "get",
				sql: sqlString.format("select * from user where name= ?", [_body.userName]),
			})
			// 判断当前的秘钥和穿过来的秘钥是否相同
			if (_md5(`${cur_user_info.name};${cur_user_info.secretKey};${_body.timeStamp};`) === _body.ciphertext) {
				log4js.info(`数据验证通过 | ${ctx.url} | ${JSON.stringify(_body)}`)
				verificationOk = true;
			} else {
				ctx.fail({
					message: "验证失败"
				})
			}
		} else {
			ctx.fail({
				message: "验证失败"
			})
		}
		
		if (verificationOk) {
			await next()
		}
		
		
	}
}


module.exports = new middleware();

